﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace Msdn5.Framework
{
    /// <summary>
    /// 一堆String类型的扩展方法
    /// </summary>
    public static class StringHelper
    {

        /// <summary>
        /// 字符串转义\ " {}
        /// </summary>
        /// <param name="source">字符串</param>
        /// <param name="noBrace">是否排除{}一般用在正则中,默认不排除</param>
        /// <returns>转义后的字符</returns>
        public static string StringEscape(this string source, bool noBrace = false)
        {
            string result = string.Empty;
            //转义 \ " {}
            if (!string.IsNullOrEmpty(source))
            {
                result = source.Replace("\\", "\\\\").Replace("\"", "\\\"");//.Replace("{", "{{").Replace("}", "}}");
            }
            else
            {
                result = "";
            }
            if (!noBrace)
            {
                result = result.Replace("{", "{{").Replace("}", "}}");
            }
            return result;
        }

        /// <summary>
        /// 获取单个匹配结果
        /// </summary>
        /// <param name="reString">原始字符串</param>
        /// <param name="regexCode">当前正则表达式</param> 
        /// <param name="regexOptions">引擎配置选项,默认为None</param>
        /// <returns>单个匹配结果</returns>
        public static System.Collections.Specialized.NameValueCollection GetRegStr(this string reString, string regexCode = "", System.Text.RegularExpressions.RegexOptions regexOptions = System.Text.RegularExpressions.RegexOptions.None)
        {
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regexCode, regexOptions);//初始化正则表达式并设置匹配模式
            System.Collections.Specialized.NameValueCollection nc = new System.Collections.Specialized.NameValueCollection();//返回的结果
            System.Text.RegularExpressions.Match m = reg.Match(reString);//执行匹配;
            System.Text.RegularExpressions.GroupCollection gc = m.Groups;//获取所有分组
            for (int i = 0; i < gc.Count; i++)
            {
                string gpName = reg.GetGroupNames()[i]; //得到组名
                string gpValue = gc[i].Value;  //得到组对应数据
                nc.Add(gpName, gpValue);
            }
            return nc;
        }


        /// <summary>
        /// 获取所有匹配结果
        /// </summary>
        /// <param name="reString">原始字符串</param>
        /// <param name="regexCode">当前正则表达式</param> 
        /// <param name="regexOptions">引擎配置选项,默认为None</param>
        /// <returns>所有匹配结果</returns>
        public static List<System.Collections.Specialized.NameValueCollection> GetRegStrs(this string reString, string regexCode = "", System.Text.RegularExpressions.RegexOptions regexOptions = System.Text.RegularExpressions.RegexOptions.None)
        {
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regexCode, regexOptions);//初始化正则表达式并设置匹配模式

            List<System.Collections.Specialized.NameValueCollection> ncList = new List<System.Collections.Specialized.NameValueCollection>(); //返回的结果集
            System.Text.RegularExpressions.MatchCollection mc = reg.Matches(reString);//执行匹配;
            for (int ic = 0; ic < mc.Count; ic++)
            {
                System.Text.RegularExpressions.GroupCollection gc = mc[ic].Groups;//获取所有分组
                System.Collections.Specialized.NameValueCollection nc = new System.Collections.Specialized.NameValueCollection();
                for (int i = 0; i < gc.Count; i++)
                {
                    string gpName = reg.GetGroupNames()[i]; //得到组名
                    string gpValue = gc[i].Value;  //得到组对应数据
                    nc.Add(gpName, gpValue);
                }
                ncList.Add(nc);
            }
            return ncList;
        }
        /// <summary>
        /// 封装了下默认的IndexOf(使用二进制且不区分大小写)
        /// 找到指定字符串为true
        /// source.IndexOf(target, StringComparison.OrdinalIgnoreCase) > -1
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <param name="target">比较的字符串</param>
        /// <returns>比较结果</returns> 
        public static bool IndexOfIgnoreCase(this string source, string target)
        {
            if (source.IsNullOrEmpty() || target.IsNullOrEmpty()) { return false; }
            return source.IndexOf(target, StringComparison.OrdinalIgnoreCase) > -1;
        }
        /// <summary>
        /// 封装了下默认的StartsWith(使用二进制且不区分大小写)
        /// StartsWith.Equals(target, StringComparison.OrdinalIgnoreCase)
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <param name="target">比较的字符串</param>
        /// <returns>比较结果</returns> 
        public static bool StartsWithIgnoreCase(this string source, string target)
        {
            if (source.IsNullOrEmpty() || target.IsNullOrEmpty()) { return false; }
            return source.StartsWith(target, StringComparison.OrdinalIgnoreCase);
        }

        /// <summary>
        /// 封装了下默认的EndsWithIgnoreCase(使用二进制且不区分大小写)
        /// EndsWith.Equals(target, StringComparison.OrdinalIgnoreCase)
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <param name="target">比较的字符串</param>
        /// <returns>比较结果</returns> 
        public static bool EndsWithIgnoreCase(this string source, string target)
        {
            if (source.IsNullOrEmpty() || target.IsNullOrEmpty()) { return false; }
            return source.EndsWith(target, StringComparison.OrdinalIgnoreCase);
        }

        /// <summary>
        /// 封装了下默认的Equals(使用二进制且不区分大小写)
        /// source.Equals(target, StringComparison.OrdinalIgnoreCase)
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <param name="target">比较的字符串</param>
        /// <returns>比较结果</returns> 
        public static bool EqualsIgnoreCase(this string source, string target)
        {
            if (source.IsNullOrEmpty() || target.IsNullOrEmpty()) { return false; }
            return source.Equals(target, StringComparison.OrdinalIgnoreCase);
        }

        /// <summary>
        /// 封装了下默认的Split免得老写一大坨代码
        /// </summary>
        /// <param name="source">调用的字符串</param>
        /// <param name="splitString">默认分隔字符串为\r\n</param>
        /// <returns>分隔后的数组</returns>
        public static string[] Split(this string source, string splitString = "\r\n") => source.SplitEx(splitString);
        /// <summary>
        /// 封装了下默认的Split免得老写一大坨代码
        /// </summary>
        /// <param name="source">调用的字符串</param>
        /// <param name="splitString">默认分隔字符串为\r\n</param>
        /// <returns>分隔后的数组</returns>
        public static string[] SplitEx(this string source, string splitString = "\r\n") => source.Split(new string[] { splitString }, StringSplitOptions.RemoveEmptyEntries);
        /// <summary>
        /// 判断是否为空
        /// string.IsNullOrWhiteSpace(source)
        /// </summary>
        /// <param name="source">当前字符串</param>
        /// <returns>系统 IsNullOrWhiteSpace 的结果</returns>
        public static bool IsNullOrEmpty(this string source) => string.IsNullOrWhiteSpace(source);
        /// <summary>
        /// 判断是否不为空
        /// !string.IsNullOrWhiteSpace(source)
        /// </summary>
        /// <param name="source">当前字符串</param>
        /// <returns>系统 IsNullOrWhiteSpace 的取反结果</returns>
        public static bool NotNullOrEmpty(this string source) => !string.IsNullOrWhiteSpace(source);
        /// <summary>
        /// 打开指定URL openType:0使用IE打开,!=0 使用默认浏览器打开
        /// </summary>
        /// <param name="url">需要打开的地址</param>
        /// <param name="openType">0使用IE,其他使用默认</param>
        public static void OpenUrl(this string url, int openType = 0)
        {
            // 调用ie打开网页
            if (openType == 0)
            {
                System.Diagnostics.Process.Start("IEXPLORE.EXE", url);

            }
            else
            {
                System.Diagnostics.Process.Start(url);
            }
        }
        /// <summary>
        /// 打开一个文件夹
        /// </summary>
        /// <param name="dirPath">文件夹地址</param>
        public static void OpenDir(this string dirPath)
        {
            System.Diagnostics.Process.Start("explorer.exe", dirPath);
        }
        /// <summary>
        /// 封装string.Join将集合数组快速转为字符串
        /// </summary>
        /// <typeparam name="T">集合数据类型</typeparam>
        /// <param name="array">集合</param>
        /// <param name="separator">分隔符</param>
        /// <returns>组成的字符串</returns>
        public static string Join<T>(this IEnumerable<T> array, string separator)
        {
            return string.Join(separator, array.ToArray());
        }
        /// <summary>
        /// HttpHeader转换为字典格式
        /// </summary>
        /// <param name="headerSource">字符串数据</param>
        /// <param name="urlEncoding">是否URL编码VALUE,默认False</param>
        /// <returns>字典形式的数据(Key/Value)</returns>
        public static Dictionary<string, string> ToHttpHeader(this string headerSource, bool urlEncoding = false)
        {
            return headerSource.ToDic(urlEncoding: urlEncoding);
        }
        /// <summary>
        /// HttpCookie转换为字典格式
        /// </summary>
        /// <param name="cookieSource">字符串数据</param>
        /// <param name="urlEncoding">是否URL编码VALUE,默认False</param>
        /// <returns>字典形式的数据(Key/Value)</returns>
        public static Dictionary<string, string> ToHttpCookie(this string cookieSource, bool urlEncoding = false)
        {
            return cookieSource.ToDic("=", "; ", urlEncoding, true);
        }
        /// <summary>
        /// 排序的字典格式
        /// </summary>
        /// <param name="paramSource">字符串数据</param>
        /// <param name="urlEncoding">是否URL编码VALUE,默认False</param>
        /// <returns>排序的字典形式的数据(Key/Value)</returns>
        public static SortedDictionary<string, string> ToSortedDictionary(this string paramSource, bool urlEncoding = false)
        {
            return new SortedDictionary<string, string>(paramSource.ToDic("=", "&", urlEncoding, false));
        }
        /// <summary>
        /// Http参数转换为排序的字典格式
        /// </summary>
        /// <param name="paramSource">字符串数据</param>
        /// <param name="urlEncoding">是否URL编码VALUE,默认False</param>
        /// <returns>排序的字典形式的数据(Key/Value)</returns>
        public static SortedDictionary<string, string> ToHttpParamDictionary(this string paramSource, bool urlEncoding = false)
        {
            return ToSortedDictionary(paramSource, urlEncoding);
        }
        /// <summary>
        /// 转换为Dictionary 
        /// </summary>
        /// <param name="source">需要转换的字符串</param>
        /// <param name="splitSource">每一项的分隔符,默认为:</param>
        /// <param name="splitLineSource">每一行的分隔符,默认为空,为空时使用Environment.NewLine</param>
        /// <param name="urlEncoding">是否对val进行url编码默认False</param> 
        /// <param name="isCookie">是否为Cookie模式,默认为False,如果为Cookie模式,且Value存在逗号、封号时，Value被包括在双引号内</param>
        /// <returns>key/value Dictionary对象</returns> 
        public static Dictionary<string, string> ToDic(this string source, string splitSource = ":", string splitLineSource = "", bool urlEncoding = false, bool isCookie = false)
        {
            if (source.IsNullOrEmpty())
            {
                throw new ArgumentNullException("要解析的参数不能为Null");
            }
            splitLineSource = string.IsNullOrEmpty(splitLineSource) ? Environment.NewLine : splitLineSource;
            Dictionary<string, string> dic = new Dictionary<string, string>();
            var strs = source.Split(new string[] { splitLineSource, "\n" }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < strs.Length; i++)
            {
                try
                {
                    var index = strs[i].IndexOf(splitSource);
                    if (index > 0)
                    {
                        string key = strs[i].Substring(0, index).Replace(" ", "");
                        string value = strs[i].Substring(index + 1).Replace(" ", "");
                        if (urlEncoding) { value = value.UrlEncoding(); }
                        if (isCookie)
                        {
                            if (value.IndexOf(",") > 0 || value.IndexOf(";") > 0)
                            {
                                value = $"\"{value.Trim()}\""; //微软官方推荐的方法
                                //value = value.urlEncoding();
                            }
                        }
                        if (!dic.ContainsKey(key))
                        {
                            dic.Add(key.Trim(), value.Trim());
                        }
                        else
                        {
                            dic[key] = value;
                        }
                    }
                }
                catch
                {
                    continue;
                }

            }
            return dic;
        }


        /// <summary>
        /// GZIP压缩
        /// </summary>
        /// <param name="buffer">需要压缩的数据</param>
        /// <returns>压缩后的字节数组</returns>
        public static byte[] GzipCompress(this byte[] buffer)
        {

            using (MemoryStream msTemp = new MemoryStream())
            {
                using (GZipStream gz = new GZipStream(msTemp, CompressionMode.Compress, true))
                {
                    gz.Write(buffer, 0, buffer.Length);
                    gz.Close();
                    gz.Dispose();
                    using (var ms = new MemoryStream(msTemp.GetBuffer(), 0, (int)msTemp.Length))
                    {
                        return ms.ToArray();
                    }
                }
            }


        }
        /// <summary>
        /// GZipStream解压字符串
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static byte[] GzipDecompress(this byte[] sourceBytes)
        {
            byte[] buffer = new byte[100];
            int length = 0;
            using (GZipStream gz = new GZipStream(new MemoryStream(sourceBytes), CompressionMode.Decompress))
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    while ((length = gz.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        ms.Write(buffer, 0, length);
                    }

                    return ms.ToArray();
                }

            }
        }
        /// <summary>
        /// 转换字符串到字节数组
        /// 转换失败时返回Null,异常由option参数接收,如果没有填写option,则会抛出
        /// </summary>
        /// <param name="source">数据源</param>
        /// <param name="option">转换的设置</param>
        /// <returns>字节数组</returns>
        public static byte[] ToBytes(this string source, ParsingOption option = null)
        {
            byte[] buffer = null;
            try
            {
                if (option == null)
                {
                    option = new ParsingOption();
                }
                if (source.IsNullOrEmpty())
                {
                    throw new ArgumentNullException();
                }
                switch (option.ParsingMode)
                {
                    case ParsingModeEnum.Base64:
                        buffer = source.ToBase64Bytes(option.ErrorCallBack);
                        break;
                    case ParsingModeEnum.Hex:
                        buffer = source.ToHexBytes(option.ErrorCallBack);
                        break;
                    case ParsingModeEnum.Encoding:
                    default:
                        buffer = option.ParsingEncoding.GetBytes(source);
                        break;
                }

            }
            catch (Exception ex)
            {
                if (option.ErrorCallBack != null)
                {
                    option.ErrorCallBack?.Invoke(ex);
                }
                else
                {
                    throw ex;
                }
            }
            return buffer;
        }
        /// <summary>
        /// 字节数组转字符串
        /// 转换失败时返回Null,异常由option参数接收,如果没有填写option,则会抛出
        /// </summary>
        /// <param name="buffer">数据源</param>
        /// <param name="option">转换的设置</param>
        /// <returns>转换后的字符串</returns>
        public static string ToStr(this byte[] buffer, ParsingOption option = null)
        {
            string result = null;
            try
            {
                if (option == null)
                {
                    option = new ParsingOption();
                }
                if (buffer == null)
                {
                    throw new ArgumentNullException();
                }
                switch (option.ParsingMode)
                {
                    case ParsingModeEnum.Base64:
                        result = buffer.ToBase64String();
                        break;
                    case ParsingModeEnum.Hex:
                        result = buffer.ToHexStr();
                        break;
                    case ParsingModeEnum.Encoding:
                    default:
                        result = option.ParsingEncoding.GetString(buffer);
                        break;
                }
            }
            catch (Exception ex)
            {
                if (option.ErrorCallBack != null)
                {
                    option.ErrorCallBack?.Invoke(ex);
                }
                else
                {
                    throw ex;
                }
            }

            return result;
        }




        /// <summary>
        /// Html编码 
        /// </summary>
        /// <param name="param">需要编码的字符</param>
        /// <returns>返回编码后数据</returns>
        public static string HtmlEncode(this string source)
        {
            return source.UnicodeEncoding("&#");
        }
        /// <summary>
        /// Html解码 
        /// </summary>
        /// <param name="param">需要解码的字符</param>
        /// <returns>返回解码后数据</returns>
        public static string HtmlDecode(this string source)
        {
            return source.UnicodeDecoding("&#");
        }

        #region BASE64 编码/解码


        /// <summary>
        /// Base64 编码
        /// </summary>
        /// <param name="buffer">byte数组</param>
        /// <returns>Base64字符串结果</returns>
        public static string ToBase64String(this byte[] buffer)
        {
            return Convert.ToBase64String(buffer, 0, buffer.Length);
        }

        /// <summary>
        /// BASE64 解码
        /// </summary>
        /// <param name="source">源字符串</param> 
        /// <param name="errorCallBack">异常回调</param>
        /// <returns>解码后的byte数组结果</returns>
        public static byte[] ToBase64Bytes(this string source, Action<Exception> errorCallBack = null)
        {
            try
            {
                return Convert.FromBase64String(source);
            }
            catch (Exception ex)
            {
                CallBackOrThrow(errorCallBack, ex);
                return null;
            }

        }
        #endregion

        #region 其他字符串/Bytes互转方法
        /// <summary>
        /// 快速替换方法(主要是给ToHexStr 清理-用)
        /// </summary>
        /// <param name="source">需要清理的字符串</param>
        /// <param name="oldparam">需要替换的字符,默认为-</param>
        /// <param name="newparam">替换后的字符,默认为空白</param>
        /// <returns></returns>
        public static string RepString(this string source, string oldparam = "-", string newparam = "")
        {
            return source.Replace(oldparam, newparam);
        }
        /// <summary>
        /// 字符串转换为十六进制字符串，每字节表示为两位,数据格式 1A2B3C转换为 1A 2B 3C 的字节数组
        /// </summary>
        /// <param name="source">要转换的字符串</param>
        /// <param name="errCallBack">异常回调</param>
        /// <returns>字节数组结果</returns>
        public static byte[] ToHex2Bytes(this string source, Action<Exception> errCallBack = null)
        {
            byte[] buffer = new byte[source.Length / 2];
            try
            {
                for (int i = 0; i < source.Length; i += 2) buffer[i / 2] = Convert.ToByte(source.Substring(i, 2), 16);
            }
            catch (Exception ex)
            {
                errCallBack?.Invoke(ex);
                return null;
            }
            return buffer;
        }

        /// <summary>
        /// 字符串 转 十六进制表示的字符串
        /// </summary>
        /// <param name="source">数据源</param>
        /// <param name="option">转换设置</param>
        /// <returns>十六进制表示的字符串</returns>
        public static string StrToHexStr(this string source, ParsingOption option = null)
        {
            return source.ToBytes(option).ToHexStr();
        }
        /// <summary>
        /// 转换为十六进制表示的字符串
        /// </summary>
        /// <param name="buffer">数组</param>
        /// <returns>十六进制字符串</returns>
        public static string ToHexStr(this byte[] buffer)
        {
            return BitConverter.ToString(buffer);
        }





        /// <summary>
        /// HexStr 转换为Hex表示的十六进制Bytes
        /// 可以直接传 "1A2B3C" "1A 2B 3C" "1A-2B-3C" 以上三种格式数据
        /// </summary>
        /// <param name="hexSource">需要转换的字符串</param>
        /// <param name="errorCallBack">异常回调</param>
        /// <returns>Hex表示的十六进制Bytes</returns>
        public static byte[] ToHexBytes(this string hexSource, Action<Exception> errorCallBack = null)
        {

            List<byte> buffer = new List<byte>();
            try
            {
                string[] ins = null;
                if (hexSource.IndexOf(" ") > 0 || hexSource.IndexOf("-") > 0)
                {
                    string instr = hexSource.Replace(" ", "-");
                    ins = instr.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 0; i < ins.Length; i++)
                    {
                        buffer.Add(byte.Parse(ins[i], System.Globalization.NumberStyles.HexNumber));
                    }
                }
                else
                {
                    buffer = new List<byte>(hexSource.ToHex2Bytes());
                }

            }
            catch (Exception ex)
            {
                CallBackOrThrow(errorCallBack, ex);
            }

            return buffer.ToArray();
        }






        #endregion

        #region URL编码/解码

        /// <summary>
        /// Url编码,encoding默认为utf8编码
        /// </summary>
        /// <param name="source">需要编码的字符串</param>
        /// <param name="encoding">指定编码类型</param>
        /// <returns>编码后的字符串</returns>
        public static string UrlEncoding(this string source, Encoding encoding = null)
        {
            if (encoding == null) { encoding = Encoding.UTF8; }
            return System.Web.HttpUtility.UrlEncode(source, encoding);
        }

        /// <summary>
        /// Url解码,encoding默认为utf8编码
        /// </summary>
        /// <param name="source">需要解码的字符串</param>
        /// <param name="encoding">指定解码类型</param>
        /// <returns>解码后的字符串</returns>
        public static string UrlDecoding(this string source, Encoding encoding = null)
        {
            if (encoding == null) { encoding = Encoding.UTF8; }
            return System.Web.HttpUtility.UrlDecode(source, encoding);
        }
        #endregion

        #region Unicode编码/解码
        /// <summary>
        /// Unicode解码 默认解\u1234 
        /// </summary>
        /// <param name="source">解码的参数</param>
        /// <param name="splitString">分隔结果</param>
        /// <param name="errorCallBack">异常回调</param>
        /// <returns>解码后的结果</returns>
        public static string UnicodeDecoding(this string source, string splitString = "u", Action<Exception> errorCallBack = null)
        {
            try
            {
                string regexCode = splitString == "u" ? "\\\\u(\\w{1,4})" : splitString + "(\\w{1,4})";
                string reString = source;
                System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regexCode);
                System.Text.RegularExpressions.MatchCollection mc = reg.Matches(reString);
                for (int i = 0; i < mc.Count; i++)
                {
                    try
                    {
                        var outs = (char)int.Parse(mc[i].Groups[1].Value, System.Globalization.NumberStyles.HexNumber);
                        source = source.Replace(mc[i].Groups[0].Value, outs.ToString());
                    }
                    catch
                    {
                        continue;
                    }
                }

            }
            catch (Exception ex)
            {
                CallBackOrThrow(errorCallBack, ex);
            }
            return source;
        }
        /// <summary>
        /// 执行回调函数还是抛出异常
        /// </summary>
        /// <param name="errorCallBack">回调函数</param>
        /// <param name="ex">异常信息</param>
        public static void CallBackOrThrow(Action<Exception> errorCallBack, Exception ex)
        {
            if (errorCallBack != null)
            {
                errorCallBack.Invoke(ex);
            }
            else
            {
                throw ex;
            }
        }
        /// <summary>
        /// Unicode编码 默认\u1234 
        /// </summary>
        /// <param name="param">编码的参数</param>
        /// <param name="SplitString">分隔结果</param>
        /// <returns>编码后结果</returns>
        public static string UnicodeEncoding(this string param, string SplitString = "\\u")
        {
            string outStr = "";
            for (int i = 0; i < param.Length; i++)
            {
                try
                {
                    outStr += SplitString + ((int)param[i]).ToString("x4");
                }
                catch
                {
                    outStr += param[i];
                    continue;
                }

            }

            return outStr;
        }
        #endregion

        /// <summary>
        /// 固定字符串长度,不够向右填充
        /// </summary>
        /// <param name="str">源字符串</param>
        /// <param name="len">固定的长度</param>
        /// <param name="paddingchar">填充内容,默认*</param> 
        /// <returns>填充后的长度</returns>
        public static string FixStrLen4Right(this string str, int len = 32, char paddingchar = '*')
        {
            if (str.Length < len)
            {
                str = str.PadRight(len, paddingchar);
            }
            if (str.Length > len)
            {
                str = str.Substring(0, len);
            }
            return str;
        }
        /// <summary>
        /// 固定字符串长度,不够向左填充
        /// </summary>
        /// <param name="str">源字符串</param>
        /// <param name="len">固定的长度</param>
        /// <param name="paddingchar">填充内容,默认*</param> 
        /// <returns>填充后的长度</returns>
        public static string FixStrLen4Left(this string str, int len = 32, char paddingchar = '*')
        {
            if (str.Length < len)
            {
                str = str.PadLeft(len, paddingchar);
            }
            if (str.Length > len)
            {
                str = str.Substring(0, len);
            }
            return str;
        }
    }
}
